package com.wdc.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wdc.common.BaseResponse;
import com.wdc.common.ErrorCode;
import com.wdc.common.ResultUtils;
import com.wdc.exception.BusinessException;
import com.wdc.model.domain.User;
import com.wdc.model.request.UserLoginRequest;
import com.wdc.model.request.UserRegisterRequest;
import com.wdc.model.vo.UserVO;
import com.wdc.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;


import static com.wdc.common.ErrorCode.*;
import static com.wdc.contant.UserConstant.USER_LOGIN_STATE;


@RestController
@RequestMapping("/user")
@Slf4j
//@CrossOrigin(origins = {"http://localhost:5173/"})
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;




    @GetMapping("/search/tags")
    public BaseResponse<List<User>>  searchUserByTags(@RequestParam List<String> tagNameList){
        List<User> userList = userService.searchUsersByTags(tagNameList);
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new RuntimeException("lll");
        }

        return ResultUtils.success(userList);
    }

    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user , HttpServletRequest request){
        //1.校验参数是否为空
        if (user == null){
            throw new RuntimeException("参数错误");
        }
        //2.校验用户权限
        //3.触发更新
        User loginUser = userService.getLoginUser(request);

        int result = userService.updateUser(user,loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest,HttpServletRequest request){
        if (userLoginRequest == null){
            return ResultUtils.error(PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        User user = userService.userLogin(userLoginRequest,request);
        if (user == null){
            return ResultUtils.error(NOT_LOGIN,"登录失败");
        }
        return ResultUtils.success(user);
    }


    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null){
            throw new BusinessException(NOT_LOGIN);
        }
        Long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(HttpServletRequest request, long pageSize , long pageNum){
        //根据不同的用户来更新缓存 完成推荐
        User loginUser = userService.getLoginUser(request);
        String redisKey = String.format("wdc:user:recommend:%s", loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        //如果有缓存就直接走缓存
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if (userPage != null){
            return ResultUtils.success(userPage);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        //最后如果走的内存就把读的写入缓存
        try {
            valueOperations.set(redisKey,userPage,30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {

            log.error("redis set key error",e);
        }

        return ResultUtils.success(userPage);

    }


    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, user));
    }


    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("用户退出")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        if (request == null){
            throw new BusinessException(PARAMS_ERROR);
        }
        Integer result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 用户注册
     * @param userRegisterRequest
     * @param request
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public BaseResponse<User> userRegister(@RequestBody UserRegisterRequest userRegisterRequest ,HttpServletRequest request){
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StrUtil.isBlank(userAccount) || StrUtil.isBlank(userPassword) ||StrUtil.isBlank(checkPassword) ) {
            throw new BusinessException(NULL_ERROR);
        }
        User user = userService.userRegister(userRegisterRequest,request);
        return ResultUtils.success(user);
    }




    @GetMapping("/{id}")
    @ApiOperation("根据 id 获取用户")
    public BaseResponse<UserVO> getUserById(@PathVariable Long id, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (id == null){
            throw new BusinessException(NULL_ERROR);
        }
        if (loginUser == null){
            throw new BusinessException(NOT_LOGIN);
        }
        UserVO userVo = userService.getUserById(id,loginUser.getId());

        return ResultUtils.success(userVo);

    }



}
